from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


driver = webdriver.Edge()

try:
    driver.get("https://op.gg/lol/champions?position=top") # 注意：你给的HTML是上单Riven
    wait = WebDriverWait(driver, 10)
    
    # 等待至少一行数据出现
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "tbody tr")))
    
    # 找到所有行
    rows = driver.find_elements(By.CSS_SELECTOR, "tbody tr")
    champion_list = []
    
    for row in rows:
        # 1. 提取排名
        try:
            rank = row.find_element(By.CSS_SELECTOR, 'td:first-child span.text-gray-400').text
        except:
            rank = "N/A"
        
        # 2. 提取英雄名
        try:
            name = row.find_element(By.CSS_SELECTOR, 'strong.text-xs').text
        except:
            name = "N/A"
            
        # 3. 提取头像链接 (可选)
        try:
            image_url = row.find_element(By.CSS_SELECTOR, 'img.rounded').get_attribute('src')
        except:
            image_url = "N/A"
        
        # 4. 提取胜率
        try:
            # 第5个<td>元素
            win_rate = row.find_elements(By.CSS_SELECTOR, 'td')[4].text 
        except:
            win_rate = "N/A"
        
        # 5. 提取选取率
        try:
            # 第6个<td>元素
            pick_rate = row.find_elements(By.CSS_SELECTOR, 'td')[5].text 
        except:
            pick_rate = "N/A"
        
        # 6. 提取禁用率 (可能在隐藏的列中)
        try:
            # 寻找第7个<td>，并且它有特定的类（根据实际情况调整选择器）
            ban_rate = row.find_element(By.CSS_SELECTOR, 'td.hidden.md\\:table-cell').text
            # 或者更稳妥的方法：直接取第7个td（索引6）
            # ban_rate = row.find_elements(By.CSS_SELECTOR, 'td')[6].text
        except:
            ban_rate = "N/A"
        
        # 7. 提取克制英雄列表
        counter_champs = []
        try:
            counter_imgs = row.find_elements(By.CSS_SELECTOR, 'ul li a img.rounded-full')
            for img in counter_imgs:
                champ_name = img.get_attribute('alt')
                if champ_name:
                    counter_champs.append(champ_name)
        except:
            pass # 如果找不到克制英雄，就留空列表
        
        # 将提取的数据存入字典
        champ_data = {
            "Rank": rank,
            "Champion": name,
            "Image_URL": image_url,
            "Win_Rate": win_rate,
            "Pick_Rate": pick_rate,
            "Ban_Rate": ban_rate,
            "Countered_By": ", ".join(counter_champs) # 将列表转为字符串，用逗号分隔
        }
        
        champion_list.append(champ_data)
        # 打印单条数据看看效果
        print(f"#{rank}: {name} - WR: {win_rate}, PR: {pick_rate}")

    # 现在champion_list里就是所有英雄的数据了
    # 你可以用pandas把它变成DataFrame并保存为CSV
    import pandas as pd
    df = pd.DataFrame(champion_list)
    df.to_csv('opgg_top_tier_list.csv', index=False, encoding='utf-8-sig')
    print("数据已保存！")

finally:
    driver.quit()